<template>
	<div>
		<el-card class="!border-none mb-4" shadow="never">
			<div class="flex flex-wrap">
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">累计充值金额</div>
					<div class="text-6xl">{{ pager.extend.total }}</div>
				</div>
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">充值成功金额</div>
					<div class="text-6xl">{{ pager.extend.success }}</div>
				</div>
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">充值成功笔数</div>
					<div class="text-6xl">{{ pager.extend.success_count }}</div>
				</div>
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">充值中金额</div>
					<div class="text-6xl">{{ pager.extend.ing }}</div>
				</div>
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">充值失败金额</div>
					<div class="text-6xl">{{ pager.extend.error }}</div>
				</div>
			</div>
		</el-card>
		<el-card class="!border-none mb-4" shadow="never">
			<el-form class="mb-[-16px]" :model="queryParams" inline label-width="auto">
				<el-form-item label="用户信息" prop="user_id">
					<el-input class="w-[200px]" v-model="queryParams.user_info" clearable placeholder="账号/邀请码" />
				</el-form-item>
				<el-form-item label="订单编号" prop="sn">
					<el-input class="w-[200px]" v-model="queryParams.sn" clearable placeholder="请输入订单编号" />
				</el-form-item>
				<el-form-item label="充值方式">
					<el-select class="w-[200px]" v-model="queryParams.method_id">
						<el-option label="全部" value />
						<el-option v-for="item in optionsData.methods" :key="item.id"
							:label="item.lang_name+' - '+item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="订单状态" prop="status">
					<el-select class="w-[200px]" v-model="queryParams.status" clearable placeholder="请选择订单状态">
						<el-option label="全部" value=""></el-option>
						<el-option v-for="(item, index) in dictData.recharge_status" :key="index" :label="item.name"
							:value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="金额范围" prop="money_min">
					<el-input class="w-[200px]" v-model="queryParams.money_min" clearable placeholder="金额大于等于" />
				</el-form-item>
				<el-form-item label="金额范围" prop="money_max">
					<el-input class="w-[200px]" v-model="queryParams.money_max" clearable placeholder="金额小于等于" />
				</el-form-item>
				<el-form-item label="下单时间">
					<daterange-picker v-model:startTime="queryParams.start_time"
						v-model:endTime="queryParams.end_time" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="resetPage">查询</el-button>
					<el-button @click="resetParams">重置</el-button>
					<export-data v-perms="['finance.recharge_record/export']" class="ml-2.5"
						:fetch-fun="rechargeRecordLists" :params="queryParams" :page-size="pager.size" />
				</el-form-item>
			</el-form>
		</el-card>
		<el-card class="!border-none" v-loading="pager.loading" shadow="never">
			<el-button v-perms="['finance.recharge_record/delete']" :disabled="!selectData.length"
				@click="handleDelete(selectData)">
				删除
			</el-button>
			<div class="mt-4">
				<el-table :data="pager.lists" :row-class-name="tableRowClassName"
					@selection-change="handleSelectionChange">
					<el-table-column type="selection" min-width="55" />
					<el-table-column label="用户" min-width="220">
						<template #default="{ row }">
							<div>账号：{{row.mobile}}</div>
							<div>邀请码：{{row.u_sn}}</div>
						</template>
					</el-table-column>
					<el-table-column label="用户层级" min-width="160" show-tooltip-when-overflow>
						<template #default="{ row }">
							<div>上级：{{row.team_top.prev_account}}</div>
							<div>一代：{{row.team_top.top_account}}</div>
							<div>代数：{{row.team_top.level}}</div>
						</template>
					</el-table-column>
					<el-table-column label="订单编号" prop="sn" min-width="130" />
					<el-table-column label="充值方式" min-width="120">
						<template #default="{ row }">
							<div>{{row.method.name}}</div>
							<div class="text-danger">{{row.method_account}}</div>
						</template>
					</el-table-column>
					<el-table-column label="充值金额" min-width="160">
						<template #default="{ row }">
							<div class="flex">充值金额：{{row.amount}}
								<popover-input v-if="row.status == 0" v-perms="['finance.recharge_record/changeAmount']" type="number"
									@confirm="handleAmount($event,row.id)" :limit="32" placeholder="请输入充值金额">
									<el-button type="primary" link>
										<icon name="el-icon-EditPen" />
									</el-button>
								</popover-input>
							</div>
							<div>实际金额：{{formatMoney(row.symbol,row.amount_act)}}</div>
							<div>汇率：{{row.rate}}</div>
							<div v-if="row.status!=0">用户余额：{{row.user_money}}</div>
						</template>
					</el-table-column>
					<el-table-column label="支付凭证">
						<template #default="{ row }">
							<image-contain v-if="row.voucher" :src="row.voucher" :width="60" :height="45"
								:preview-src-list="[row.voucher]" preview-teleported fit="contain" />
						</template>
					</el-table-column>
					<el-table-column label="状态" prop="status" min-width="100">
						<template #default="{ row }">
							<dict-value :options="dictData.recharge_status" :value="row.status" />
						</template>
					</el-table-column>
					<el-table-column label="下单时间" min-width="120">
						<template #default="{ row }">
							<div>{{row.create_time}}</div>
						</template>
					</el-table-column>
					<el-table-column label="操作" fixed="right" min-width="150">
						<template #default="{ row }">
							<el-button v-if="row.status == 0" v-perms="['finance.recharge_record/agree']" type="primary"
								link @click="handleAgree(row)">
								同意
							</el-button>
							<el-button v-if="row.status == 0" v-perms="['finance.recharge_record/agree']" type="primary"
								link @click="handleRefuse(row)">
								拒绝
							</el-button>
							<el-button v-perms="['finance.recharge_record/delete']" type="danger" link
								@click="handleDelete(row.id)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="flex mt-4 justify-end">
				<pagination v-model="pager" @change="getLists" />
			</div>
		</el-card>
	</div>
</template>

<script lang="ts" setup name="rechargeRecordLists">
	import { usePaging } from '@/hooks/usePaging'
	import { useDictData, useDictOptions } from '@/hooks/useDictOptions'
	import { rechargeRecordLists, rechargeRecordDelete, rechargeRecordAgree, rechargeRecordRefuse, rechargeRecordRemark,rechargeRecordChangeAmount } from '@/api/finance'
	import { apiRechargeMethodAll } from '@/api/setting/recharge_method'
	import feedback from '@/utils/feedback'
	import { isEmpty } from '@/utils/util'

	let timer : any = null
	// 查询条件
	const queryParams = reactive({
		sn: '',
		u_sn: '',
		user_info: '',
		method_id: '',
		status: '',
		money_min: '',
		money_max: '',
		start_time: '',
		end_time: '',
		parent_sn: '',
		level: ''
	})

	// 选中数据
	const selectData = ref<any[]>([])

	// 表格选择后回调事件
	const handleSelectionChange = (val : any[]) => {
		selectData.value = val.map(({ id }) => id)
	}

	// 获取字典数据
	const { dictData } = useDictData('recharge_status')

	// 分页相关
	const { pager, getLists, resetParams, resetPage } = usePaging({
		fetchFun: rechargeRecordLists,
		params: queryParams
	})

	const { optionsData } = useDictOptions<{
		methods : any[]
	}>({
		methods: {
			api: apiRechargeMethodAll
		}
	})

	// 同意充值
	const handleAgree = async (id : number | any[]) => {
		await feedback.confirm('确定要同意？')
		await rechargeRecordAgree({ id })
		getLists()
	}

	// 拒绝充值
	const handleRefuse = async (id : number | any[]) => {
		await feedback.confirm('确定要拒绝？')
		await rechargeRecordRefuse({ id })
		getLists()
	}

	// 删除
	const handleDelete = async (id : number | any[]) => {
		await feedback.confirm('确定要删除？')
		await rechargeRecordDelete({ id })
		getLists()
	}

	const handleRemark = async (value : string, field : string, id : number) => {
		if (isEmpty(value)) return
		await rechargeRecordRemark({ id: id, content: value })
		getLists()
	}
	
	const handleAmount = async (value : number, id : number) => {
		if (isEmpty(value)) {
			return
		}
		if (value <= 0) {
			return feedback.msgError('请输入正确的金额')
		}
		await rechargeRecordChangeAmount({ id: id, amount: value })
		getLists()
	}
	
	const tableRowClassName = ({ row, rowIndex, } : {
		row : any
		rowIndex : number
	}) => {
		if (row['remark2'] != "") {
			return 'warning-row'
		}
		return ''
	}
	
	const formatMoney = (symbol : string, money : string) => {
		let regex = /^[a-zA-Z]+$/; // 正则表达式，匹配只有英文字母的情况
		if (regex.test(symbol)) {
			return money + " " + symbol;
		} else {
			return symbol + money;
		}
	}
	
	const getTimer = async () => {
		timer = setInterval(() => {
			if (localStorage.getItem('refresh_recharge') == '1') {
				localStorage.setItem('refresh_recharge', '0');
				resetPage();
			}
		}, 5000)
	}

	getLists()
	getTimer()
	onUnmounted(() => {
		timer && clearInterval(timer)
	})
</script>

<style>
	.el-table .warning-row {
		--el-table-tr-bg-color: var(--el-color-warning-light-9);
	}

	.el-table .success-row {
		--el-table-tr-bg-color: var(--el-color-success-light-9);
	}
</style>